package com.bk.utils;

import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.InputStream;

/**
 * @Author 27435
 * @Date 2024/11/2017:20
 * @Version 1.0
 */

/**
 * Mybatis工具类，用于提供SqlSessionFactory和SqlSession对象
 */
public class MybatisUtils {

    // SqlSessionFactory对象，用于生成SqlSession
    private static SqlSessionFactory factory = null;

    // 静态代码块，用于初始化SqlSessionFactory
    static {

        // 读取MyBatis配置文件
        InputStream is = MybatisUtils.class.getClassLoader().getResourceAsStream("mybatis-config.xml");
        // 使用SqlSessionFactoryBuilder构建SqlSessionFactory
        factory = new SqlSessionFactoryBuilder().build(is);

    }

    /**
     * 获取SqlSession对象
     *
     * @return SqlSession对象，用于执行SQL语句
     */
    public static SqlSession getSqlSession(){
        SqlSession sqlSession = null;
        if (factory != null){
            // 自动提交事务为true，打开SqlSession
            sqlSession = factory.openSession(true);
        }
        return sqlSession;
    }

}
